package com.jason.quectel0805.activities;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.jason.quectel0805.R;

import androidx.appcompat.app.AppCompatActivity;

/**
 * @author：Jason
 * @date: 2022/8/10 10:25
 * @email：1129847330@qq.com
 * @description: sharedPreferences保存数据
 * 应用场景：保存轻量级的数据，比如app的配置数据(开关数据，当前登录用户的数据)
 * 当涉及到大量数据存储时，sp会非常慢，可能会导致ANR(Application not responsing)（界面卡死）
 * 此时有两种选择方式：
 * 1、开启子线程强制保存到sp（强烈不推荐）
 * 2、通过sqlite数据库来保存
 */

public class JasonSharedPreferencesActivity extends AppCompatActivity {
    private EditText etInputName;
    private EditText etInputAge;
    private SharedPreferences sharedPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jason_shared_preferences);
        etInputName = findViewById(R.id.et_sp_inputName);
        etInputAge = findViewById(R.id.et_sp_inputAge);
        //获取sharedpreferences对象
        sharedPreferences = getSharedPreferences("config", Context.MODE_PRIVATE);
    }

    /**
     * 通过sharedPreferences保存数据
     *
     * @param view
     */
    public void saveData(View view) {
        //通过sharedpreferences获取Editor
        SharedPreferences.Editor editor = sharedPreferences.edit();
        String name = etInputName.getText().toString();
        String age = etInputAge.getText().toString();
        editor.putString("name", name);
        editor.putString("age", age);
        editor.commit();
        Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
    }

    /**
     * 通过sharedPreferences保存数据
     *
     * @param view
     */
    public void readData(View view) {
        String name = sharedPreferences.getString("name", "佚名");
        String age = sharedPreferences.getString("age", "0");
        Toast.makeText(this, name + ", " + age, Toast.LENGTH_SHORT).show();
    }
}